<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '修改收货人',
  },
}
</route>

<script lang="ts" setup>
import type { ReceiptDto } from '@/service/app'
import { receiptControllerUpdate as updateAddress } from '@/service/app'

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
const systemInfo = uni.getWindowInfo()
const top = systemInfo.safeArea?.top ?? null
// #endif

function back() {
  uni.navigateBack()
}

// 定义接收的地址数据
// 修改后：初始化为空对象（符合 ReceiptDto 结构）
const address = ref<ReceiptDto>({
  id: null,
  userId: null,
  name: '',
  phone: '',
  area: '',
  address: '',
  isDefault: false,
})

// 页面加载时获取参数
onLoad((options: any) => {
  try {
    if (options.item) {
      const itemStr = decodeURIComponent(options.item)
      address.value = JSON.parse(itemStr)
      console.log('接收的地址数据：', address.value)
    }
    else {
      console.warn('未接收到地址参数，使用默认空对象')
      // 此时 address 已初始化为空对象，无需额外处理
    }
  }
  catch (error) {
    console.error('解析地址参数失败：', error)
    // 解析失败时保持初始空对象，避免 address 变为 undefined
    uni.showToast({ title: '数据加载失败', icon: 'none' })
  }
})

const form = ref()

function handleSubmit() {
  form.value
    .validate()
    .then(async ({ valid, errors }) => {
      if (valid) {
        const { success } = await updateAddress({ params: { id: address.value.id }, body: { userId: address.value.userId, name: address.value?.name, phone: address.value?.phone, area: address.value?.area, address: address.value?.address, isDefault: address.value?.isDefault, id: address.value.id } })
        if (success) {
          uni.showToast({
            title: '修改成功',
            icon: 'none',
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        }
        else {
          console.log(success)
        }
      }
      else {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none',
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>

<template>
  <!-- 导航栏 -->
  <view class="fixed top-0 z-20 w-full bg-white transition-all duration-300">
    <view class="bg-white" :style="{ height: `${top}px` }" />
    <view class="h-11 flex items-center bg-white px-4">
      <wd-icon name="thin-arrow-left" size="22px" @click="back" />
      <h1 class="flex-1 truncate px-6 text-lg text-gray-800 font-medium">
        修改收货人
      </h1>
    </view>
  </view>
  <view class="mt-20rpx box-border min-h-[100vh] overflow-hidden bg-[#f4f4f4] px-30rpx">
    <!-- 间隔占位 -->
    <view class="pt-80rpx" :style="{ marginTop: `${top + 20}px` }" />
    <!-- 表单填写 -->
    <view class="rounded-tl-xl rounded-tr-xl bg-white py-30rpx text-26rpx shadow-sm">
      <wd-form ref="form" :model="address">
        <wd-cell-group>
          <wd-input
            v-model="address.name"
            label="姓名"
            label-width="140rpx"
            prop="name"
            placeholder="请填写真实姓名"
            :maxlength="10"
            :rules="[{ required: true, message: '请填写真实姓名' }]"
          />
          <view class="h-10rpx" />
          <wd-input
            v-model="address.phone"
            label="手机号"
            label-width="140rpx"
            prop="phone"
            placeholder="请填写手机号"
            :maxlength="11"
            :rules="[
              { required: true, message: '请填写手机号' },
              { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
          />
          <view class="h-10rpx" />
          <wd-textarea
            v-model="address.area"
            label="所在地区"
            label-width="140rpx"
            prop="area"
            placeholder="省、市、区、街道"
            auto-height
            :rules="[{ required: true, message: '请填写所在地区' }]"
          />
          <view class="h-10rpx" />
          <wd-textarea
            v-model="address.address"
            label="详细地址"
            label-width="140rpx"
            prop="address"
            placeholder="小区楼栋、乡村名称"
            auto-height
            :rules="[{ required: true, message: '请填写详细地址' }]"
          />
        </wd-cell-group>
      </wd-form>
    </view>
    <!-- 设置默认地址 -->
    <view class="mt-20rpx flex items-center justify-between rounded-bl-xl rounded-br-xl bg-white px-30rpx py-30rpx text-26rpx shadow-sm">
      <view>设置为默认地址</view>
      <wd-switch v-model="address.isDefault" active-color="#bfa189" size="40rpx" inactive-color="#d5d5d5" />
    </view>
    <!-- 确认按钮 -->
    <view
      class="mt-50rpx flex items-center justify-center rounded-lg bg-[linear-gradient(to_right,#e0cebd,#bfa189)] px-4 py-3 text-white"
      @click="handleSubmit"
    >
      确认
    </view>
  </view>
</template>

<style lang="scss" scoped>
//
</style>
